if(!window.Berta) window.Berta = {};
if(!Berta.Pane) Berta.Pane = {};

Berta.Panel.addPaneDefinition('sections', new Class(function(){

	return {
		extend: Berta.Pane,
		
		defaults: {
			type: 'sections'
		},
		
		loading: false,
		loaded: false,
		
		
		constructor: function(options) {
			Berta.Pane.call(this, options);
			this.setTitle('Menu items');
		},
		
		//   .______    __    __  .______    __       __    ______    ////////////////////////////////////////////////////////////
		//   |   _  \  |  |  |  | |   _  \  |  |     |  |  /      |   ////////////////////////////////////////////////////////////
		//   |  |_)  | |  |  |  | |  |_)  | |  |     |  | |  ,----'   ////////////////////////////////////////////////////////////
		//   |   ___/  |  |  |  | |   _  <  |  |     |  | |  |        ////////////////////////////////////////////////////////////
		//   |  |      |  `--'  | |  |_)  | |  `----.|  | |  `----.   ////////////////////////////////////////////////////////////
		//   | _|       \______/  |______/  |_______||__|  \______|   ////////////////////////////////////////////////////////////

		
		afterOpen: /*override */ function() {
			this._(load)();
			
		},
		
		beforeClose: /* override */ function() {
			
		},
		
		sectionCreateNew: function(callback) {
			if(!callback) callback = null;
			Berta.Server.instance().post(Berta.Route.get('post:sections', null, { 'name': ''}), this._(sectionCreateNewComplete, callback));
		},
		
		sectionMoveUp: function(section, callback) {
			if(!callback) callback = null;
			var sId = section.data('sid');
			if(sId > 0) {
				Berta.Server.instance().put(Berta.Route.get('put:section-promote', { 'id': sId }), this._(sectionMoveComplete, [section, 'up', callback]));
			}
		},
		sectionMoveDown: function(section, callback) {
			if(!callback) callback = null;
			var sId = section.data('sid');
			if(sId > 0) {
				Berta.Server.instance().put(Berta.Route.get('put:section-demote', { 'id': sId }), this._(sectionMoveComplete, [section, 'down', callback]));
			}
		},
		
		sectionDelete: function(section, callback) {
			if(!callback) callback = null;
			var sId = section.data('sid');
			if(sId > 0) {
				Berta.Server.instance().del(Berta.Route.get('delete:section', { 'id': sId }), this._(sectionDeleteComplete, [section, callback]));
			}
		}
		
		
	};


	//   .______   .______     __  ____    ____  ___   .___________. _______    //////////////////////////////////////////////////
	//   |   _  \  |   _  \   |  | \   \  /   / /   \  |           ||   ____|   //////////////////////////////////////////////////
	//   |  |_)  | |  |_)  |  |  |  \   \/   / /  ^  \ `---|  |----`|  |__      //////////////////////////////////////////////////
	//   |   ___/  |      /   |  |   \      / /  /_\  \    |  |     |   __|     //////////////////////////////////////////////////
	//   |  |      |  |\  \--.|  |    \    / /  _____  \   |  |     |  |____    //////////////////////////////////////////////////
	//   | _|      | _| `.___||__|     \__/ /__/     \__\  |__|     |_______|   //////////////////////////////////////////////////

	function onSectionUpClick(event) {
		var s = $(event.target).parents('.x-se-section');
		this.sectionMoveUp(s);
	}
	function onSectionDownClick(event) {
		var s = $(event.target).parents('.x-se-section');
		this.sectionMoveDown(s);
	}
	function sectionMoveComplete(section, direction, callback, xhrId, response) {
		if(response.error) {
			alert(response.errorMessage);
		} else {
			var otherSection = (direction == 'up') ? section.prev('.x-se-section') : section.next('.x-se-section');
			if (otherSection.length > 0) {
				section.animate({'opacity': 0}, 150, function() {
					if(direction == 'up') {
						otherSection.before(section);
					} else {
						otherSection.after(section);
					}
					section.animate({'opacity': 1}, 500);
				});
			}
			this._(changeInSections)();
		}
		if(jQuery.isFunction(callback)) callback(id);
		
	}

	function onCreateNewClick(event) {
		this.sectionCreateNew();
		return false;
	}
	function sectionCreateNewComplete (callback, xhrId, response) {
		if(response.error) {
			alert(response.error);
		} else {
			var newSObj = {};
			newSObj.id = response.json.values.id;
			
			this.elements.inside.find('.x-se-container').append(this._(getRenderedSection)(newSObj));
			this._(registerEditables)();
			this._(changeInSections)();
		}
		this.fireResize();
		if(jQuery.isFunction(callback)) callback(id);
	}

	function onSectionDeleteClick(event) {
		var section = $(event.target).parents('.x-se-section');
		this.sectionDelete(section);
		return false;
	}
	function sectionDeleteComplete(section, callback, xhrId, response) {
		if(response.error) {
			alert(response.errorMessage);
			if(jQuery.isFunction(callback)) callback(id);
		} else {
			section.hide(200, this._(sectionDeleteCompleteDo, [ section, callback]));
			this._(changeInSections)();
		}
	}
	function sectionDeleteCompleteDo(section, callback) {
		
		Berta.EditorManager.instance().unregisterEditables(section.find('.x-editable'));
		section.empty().remove();
		this.fireResize();
		if(jQuery.isFunction(callback)) callback(id);
	}





	function load() {
		if (!this.loading && !this.loaded) {
			this.loading = true;
			Berta.Server.instance().get(Berta.Route.get('get:sections'), this._(loadComplete));
		}
	}
	function loadComplete(xhrId, response) {
		this.loading = false;
		if (response.error) {
			alert(response.error);
		} else {
			this.loaded = true;
			var sList = response.json;
			var html = $('<div class="x-se-container"></div>' +
						 '<div class="x-se-new-container"><hr /><a href="#" class="x-se-new">create new</a></div>')
						 	.find('.x-se-new').click(this._(onCreateNewClick)).end()
			var htmlList = html.filter('.x-se-container');
			
			// add sections to the container
			if (sList.length > 0) {
				var rFunc = this._(getRenderedSection);
				jQuery.each(sList, function(idx, s) {
					htmlList.append(rFunc(s));
				});
			}
			
			this.fill(html);

			this.fireResize();

			// init .x-editable instances
			this._(registerEditables)();
		}
	}
	
	function registerEditables() {
		Berta.EditorManager.instance().registerEditables(
			this.elements.inside.find('.x-editable'),
			'panel',	// put into the panel context as sections editor is always in the panel
			 null, //this._(onSectionEditorChange),
			 this._(changeInSections),
			 null //this._(onSectionEditorRevert)
		);
	}
	
	function changeInSections() {
		Berta.Controller.execCommand('controller:reloadMenuHTML');
	}
	

	function getRenderedSection(sObj) {
		var container = $('<div class="x-se-section">' + 
				'<a href="#" class="x-se-up">/\\</a>' +
				'<a href="#" class="x-se-down">\\/</a>'  +
				'<div class="x-se-title">' + 
					'<span class="x-editable" data-berta=\'{"editor":"Textline", "route":"put:section", "route_variables":{"id":' + sObj.id + '}, "variable":"name", "editor_params":{"tags_allowed": false, "newlines":false} }\'></span>' +
				'</div>' + 
				'<a href="#" class="x-se-delete">x</a>' +
				'<div class="x-se-published x-editable" data-berta=\'{"editor":"OnOff", "route":"put:section", "route_variables":{"id":' + sObj.id + '}, "variable":"published","editor_params":{"on":"visible","off":"hidden"}}\'>' + (sObj.published ? 'true' : 'false') + '</div>' +
			'<br class="clear" /></div>')
					 .find('.x-se-delete').click(this._(onSectionDeleteClick)).end()
					 .find('.x-se-up').click(this._(onSectionUpClick)).end()
					 .find('.x-se-down').click(this._(onSectionDownClick)).end()
					 .find('.x-se-title .x-editable').html(sObj.name ? sObj.name : '').end();

		container.data('sid', sObj.id);
		return container;	
	}


}()));
